package com.hamilton.erik.pt.server.resource;

import java.sql.SQLException;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.hamilton.erik.pt.core.dao.UserDAO;
import com.hamilton.erik.pt.core.dao.factory.DAOFactory;
import com.hamilton.erik.pt.core.dao.factory.DAOFactory.DAOFactoryType;
import com.hamilton.erik.pt.core.model.User;
import com.hamilton.erik.pt.core.util.AuthenticationUtil;

@Path("/auth")
public class AuthenticationResource {

	@POST
	@Path("/login")
	@Produces(MediaType.APPLICATION_JSON)
	public String login(@FormParam("userName") String userName,
						@FormParam("password") String password) {

		UserDAO userDao = DAOFactory
							.getDAOFactory(DAOFactoryType.H2)
								.getUserDAO();
		
		try {
			User user = userDao.findUser(userName);
			
			// Make sure a user was found
			if(user != null) {
				if(AuthenticationUtil.getInstance()
					.authenticateCredentials(user, password)) {			
				
					return AuthenticationUtil.AUTH_SUCCESS;
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return AuthenticationUtil.AUTH_FAILURE;
	}
	
	@POST
	@Path("/register")
	@Produces(MediaType.APPLICATION_JSON)
	public String register(@FormParam("userName") String userName,
							@FormParam("password") String password) {
		UserDAO userDao = DAOFactory
							.getDAOFactory(DAOFactoryType.H2)
								.getUserDAO();
		
		int result = -1;
		
		try {
			// Check if user already exists for userName
			if(userDao.userExists(userName)) {
				return AuthenticationUtil.PRE_EXISTING_USER;
			}
			
			User newUser = new User();
			
			// Salt and hash the password and store all
			// data in the DB
			String salt = AuthenticationUtil.getInstance().generateSalt();
			String hash = AuthenticationUtil.getInstance().hash(password, salt);
			
			newUser.setUserName(userName);
			newUser.setHash(hash);
			newUser.setSalt(salt);
			
			result = userDao.insertUser(newUser);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(result >= 0) {
			return AuthenticationUtil.AUTH_SUCCESS;	
		}
		else {
			return AuthenticationUtil.AUTH_FAILURE;
		}
		
	}
}
